package com.ruoyi.xqsp.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.status.ResponseUtil;
import com.ruoyi.xqsp.domain.SpChapterBuy;
import com.ruoyi.xqsp.domain.entity.UserExpenseCalendar;
import com.ruoyi.xqsp.service.*;
import com.ruoyi.xqsp.utils.XqidUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.xqsp.domain.SpExpenseCalendar;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 消费记录Controller
 *
 * @author ruoyi
 * @date 2021-05-08
 */
@RestController
@RequestMapping("/xqsp/calendar")
public class SpExpenseCalendarController extends BaseController
{
    @Autowired
    private ISpExpenseCalendarService spExpenseCalendarService;
    @Autowired
    private ISpUsersService spUsersService;
    @Autowired
    private ISpVideoService spVideoService;
    @Autowired
    private ISpVarietyVideoService spVarietyVideoService;
    @Autowired
    private ISpPhoenixServiceService spPhoenixServiceService;
    @Autowired
    private ISpComicService spComicService;
    @Autowired
    private ISpComicChapterService spComicChapterService;
    @Autowired
    private ISpChapterBuyService spChapterBuyService;

    /**
     * 查询消费记录列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:calendar:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpExpenseCalendar spExpenseCalendar)
    {
        startPage();
        List<SpExpenseCalendar> list = spExpenseCalendarService.selectSpExpenseCalendarList(spExpenseCalendar);
        TableDataInfo dataTable = getDataTable(list);
        List<UserExpenseCalendar>userExpenseCalendarList=new ArrayList<>();
        UserExpenseCalendar userExpenseCalendar;
        for(SpExpenseCalendar calendar:list){
            userExpenseCalendar=new UserExpenseCalendar();
            userExpenseCalendar.setSpExpenseCalendar(calendar);
            if (calendar.getUserId()!=null){
                if (spUsersService.selectSpUsersById(calendar.getUserId())!=null){
                    userExpenseCalendar.setUserName(spUsersService.selectSpUsersById(calendar.getUserId()).getUserName());
                }
            }


            userExpenseCalendarList.add(userExpenseCalendar);
        }
        dataTable.setRows(userExpenseCalendarList);
        return dataTable;
    }

    /**
     * 导出消费记录列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:calendar:export')")
    @Log(title = "消费记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpExpenseCalendar spExpenseCalendar)
    {
        List<SpExpenseCalendar> list = spExpenseCalendarService.selectSpExpenseCalendarList(spExpenseCalendar);
        ExcelUtil<SpExpenseCalendar> util = new ExcelUtil<SpExpenseCalendar>(SpExpenseCalendar.class);
        return util.exportExcel(list, "calendar");
    }

    /**
     * 获取消费记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:calendar:query')")
    @GetMapping(value = "/{expenseCalendarId}")
    public AjaxResult getInfo(@PathVariable("expenseCalendarId") Long expenseCalendarId)
    {
        return AjaxResult.success(spExpenseCalendarService.selectSpExpenseCalendarById(expenseCalendarId));
    }

    /**
     * 新增消费记录
     */
    @PreAuthorize("@ss.hasPermi('xqsp:calendar:add')")
    @Log(title = "消费记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpExpenseCalendar spExpenseCalendar)
    {
        String expenseCalendarOrder;

        boolean bHave=true;
        while (bHave)
        {
            expenseCalendarOrder= XqidUtils.UserRecord();
            if (spExpenseCalendarService.selectSpExpenseCalendarByExpenseCalendarOrder(expenseCalendarOrder)==null) {
                bHave=false;
                spExpenseCalendar.setExpenseCalendarOrder(expenseCalendarOrder);
            }
        }
        return toAjax(spExpenseCalendarService.insertSpExpenseCalendar(spExpenseCalendar));
    }

    /**
     * 修改消费记录
     */
    @PreAuthorize("@ss.hasPermi('xqsp:calendar:edit')")
    @Log(title = "消费记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpExpenseCalendar spExpenseCalendar)
    {
        return toAjax(spExpenseCalendarService.updateSpExpenseCalendar(spExpenseCalendar));
    }

    /**
     * 删除消费记录
     */
    @PreAuthorize("@ss.hasPermi('xqsp:calendar:remove')")
    @Log(title = "消费记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{expenseCalendarIds}")
    public AjaxResult remove(@PathVariable Long[] expenseCalendarIds)
    {
        return toAjax(spExpenseCalendarService.deleteSpExpenseCalendarByIds(expenseCalendarIds));
    }


    /**
     * 视频和综艺视频和楼凤和漫画的金币解锁设置
     * @return
     */
    @PostMapping("/unLockVideo")
    public AjaxResult unLockVideo(@RequestBody SpExpenseCalendar spExpenseCalendar){
        String expenseCalendarOrder;

        boolean bHave=true;
        while (bHave)
        {
            expenseCalendarOrder= XqidUtils.UserRecord();
            if (spExpenseCalendarService.selectSpExpenseCalendarByExpenseCalendarOrder(expenseCalendarOrder)==null) {
                bHave=false;
                spExpenseCalendar.setExpenseCalendarOrder(expenseCalendarOrder);
            }
        }
        spExpenseCalendar.setExpenseCalendarTime(new Date());
        //视频金币解锁
        if (spExpenseCalendar.getExpenseCalendarWay()==1){
            spExpenseCalendar.setExpenseCalendarGlod(spVideoService.selectSpVideoById(spExpenseCalendar.getExpenseCalendarState()).getVideoUnlockGlod());
            if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod().compareTo(spExpenseCalendar.getExpenseCalendarGlod())> -1){
                spUsersService.updateUserGlod(spExpenseCalendar.getUserId(),spExpenseCalendar.getExpenseCalendarGlod());
                spExpenseCalendarService.insertSpExpenseCalendar(spExpenseCalendar);
                return AjaxResult.success(spUsersService.selectSpUserById(spExpenseCalendar.getUserId()));
            }else {
                return AjaxResult.error1("金币不足");
            }
        }
        //漫画
        if (spExpenseCalendar.getExpenseCalendarWay()==2){
            spExpenseCalendar.setExpenseCalendarGlod(spComicService.selectSpComicById(spExpenseCalendar.getExpenseCalendarState()).getComicUnlockGlod());
            Long count=0l;
            Long a=spComicChapterService.selectSpComicChapterCountByComicId(spExpenseCalendar.getExpenseCalendarState());
            SpChapterBuy spChapterBuy = new SpChapterBuy();
            spChapterBuy.setUserId(spExpenseCalendar.getUserId());
            spChapterBuy.setComicId(spExpenseCalendar.getExpenseCalendarState());
            Long b=spChapterBuyService.selectSpChapterBuyCount(spChapterBuy);
            Long c=a-b;
          if (spExpenseCalendar.getChapterCounts()==1){//一章购买
              if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod() .compareTo( spExpenseCalendar.getExpenseCalendarGlod()) > -1) {
                  spChapterBuy.setComicChapterDirectory(spExpenseCalendar.getChapterDirectory());
                  spChapterBuyService.insertSpChapterBuy(spChapterBuy);
                  count = 1l;
              }else {
                  return AjaxResult.error1("金币不足");
              }
          }
          if (spExpenseCalendar.getChapterCounts()==2) {//十章购买
              if(c>10){
              if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod() .compareTo(spExpenseCalendar.getExpenseCalendarGlod().multiply(new BigDecimal(10)))> -1) {
                  for (Long i = spExpenseCalendar.getChapterDirectory(); i <spExpenseCalendar.getChapterDirectory()+10; i++) {
                      spChapterBuy.setComicChapterDirectory(i);
                      if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size() == 0) {
                          spChapterBuyService.insertSpChapterBuy(spChapterBuy);
                          count = count + 1;
                      }
                  }
              }else {
                  return AjaxResult.error1("金币不足");
              }
              }else {
                  if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod() .compareTo(spExpenseCalendar.getExpenseCalendarGlod().multiply(BigDecimal.valueOf(c))) >-1){
                      for (Long i = spExpenseCalendar.getChapterDirectory(); i <spExpenseCalendar.getChapterDirectory()+ c; i++) {
                          spChapterBuy.setComicChapterDirectory(i);
                          if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size() == 0) {
                              spChapterBuyService.insertSpChapterBuy(spChapterBuy);
                              count = count + 1;
                          }
                      }
                  }else {
                      return AjaxResult.error1("金币不足");
                  }
             }



          }
            if (spExpenseCalendar.getChapterCounts()==3){//五十章购买
                if (c>50){
                    if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod().compareTo(spExpenseCalendar.getExpenseCalendarGlod().multiply(new BigDecimal(50))) > -1){
                        for (Long i=spExpenseCalendar.getChapterDirectory();i<spExpenseCalendar.getChapterDirectory()+50;i++){
                            spChapterBuy.setComicChapterDirectory(i);
                            if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size()==0){
                                spChapterBuyService.insertSpChapterBuy(spChapterBuy);
                                count=count+1;
                            }
                        }
                    }else {
                        return AjaxResult.error1("金币不足");
                    }
                }else {
                    if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod() .compareTo(spExpenseCalendar.getExpenseCalendarGlod().multiply(BigDecimal.valueOf(c)))> -1){
                        for (Long i=spExpenseCalendar.getChapterDirectory();i<spExpenseCalendar.getChapterDirectory()+c;i++){
                            spChapterBuy.setComicChapterDirectory(i);
                            if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size()==0){
                                spChapterBuyService.insertSpChapterBuy(spChapterBuy);
                                count=count+1;
                            }
                        }
                    }else {
                        return AjaxResult.error1("金币不足");
                    }
                }



            }
            if (spExpenseCalendar.getChapterCounts()==4){//剩下所有章节购买

                if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod().compareTo(spExpenseCalendar.getExpenseCalendarGlod().multiply(BigDecimal.valueOf(c))) > -1){

                    for (Long i=spExpenseCalendar.getChapterDirectory();i<spExpenseCalendar.getChapterDirectory()+c;i++){
                        spChapterBuy.setComicChapterDirectory(i);
                        if (spChapterBuyService.selectSpChapterBuyList(spChapterBuy).size()==0){
                            spChapterBuyService.insertSpChapterBuy(spChapterBuy);
                            count=count+1;
                        }
                    }
                }



            }
            if (count>0){
                BigDecimal glod=spExpenseCalendar.getExpenseCalendarGlod().multiply(new BigDecimal(count)) ;
                if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod().compareTo(glod) > -1){
                    spUsersService.updateUserGlod(spExpenseCalendar.getUserId(),glod);
                    spExpenseCalendar.setExpenseCalendarGlod(glod);
                    spExpenseCalendarService.insertSpExpenseCalendar(spExpenseCalendar);
                    return AjaxResult.success(spUsersService.selectSpUserById(spExpenseCalendar.getUserId()));
                }else {
                    return AjaxResult.error1("金币不足");
                }
            }else {
                return AjaxResult.error3("章节不足");
            }


        }
//        //楼凤
//        if (spExpenseCalendar.getExpenseCalendarWay()==3){
//            spExpenseCalendar.setExpenseCalendarGlod(spPhoenixServiceService.selectSpPhoenixServiceById(spExpenseCalendar.getExpenseCalendarState()).getPhoenixUnlockGold());
//            if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod()>=spExpenseCalendar.getExpenseCalendarGlod()){
//                spUsersService.updateUserGlod(spExpenseCalendar.getUserId(),spExpenseCalendar.getExpenseCalendarGlod());
//                spExpenseCalendarService.insertSpExpenseCalendar(spExpenseCalendar);
//                spPhoenixServiceService.updateSpPhoenixServiceUnlockNum(spExpenseCalendar.getExpenseCalendarState());
//                return AjaxResult.success(spUsersService.selectSpUserById(spExpenseCalendar.getUserId()));
//            }else {
//                return AjaxResult.error1("金币不足");
//            }
//        }
//        //综艺视频
//        if (spExpenseCalendar.getExpenseCalendarWay()==4){
//            spExpenseCalendar.setExpenseCalendarGlod(Long.valueOf(spVarietyVideoService.selectSpVarietyVideoById(spExpenseCalendar.getExpenseCalendarState()).getVarietyVideoUnlockGold()));
//            if (spUsersService.selectSpUsersById(spExpenseCalendar.getUserId()).getUserGlod()>=spExpenseCalendar.getExpenseCalendarGlod()){
//                spUsersService.updateUserGlod(spExpenseCalendar.getUserId(),spExpenseCalendar.getExpenseCalendarGlod());
//                spExpenseCalendarService.insertSpExpenseCalendar(spExpenseCalendar);
//                return AjaxResult.success(spUsersService.selectSpUserById(spExpenseCalendar.getUserId()));
//            }else {
//                return AjaxResult.error1("金币不足");
//            }
//        }

      return AjaxResult.error("错误",spUsersService.selectSpUserById(spExpenseCalendar.getUserId()));
    }

//    /**
//     * 查询用户所有消费记录
//     * @return
//     */
//    @GetMapping("/getAll/{userId}")
//    public TableDataInfo getAll(@PathVariable("userId") Long userId){
//
//        startPage();
//        List<SpExpenseCalendar>spExpenseCalendarList=spExpenseCalendarService.selectSpExpenseCalendarByUserId(userId);
//        return getDataTable(spExpenseCalendarList);
//    }

    /**
     * 查询用户所有消费记录
     * @return
     */
    @GetMapping("/getAll")
    public ResponseUtil getAll(Long userId, Integer type, Integer pageNum, Integer pageSize){

        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper wrapper = new QueryWrapper();

        wrapper.eq("user_id",userId);
        switch (type){
            case 1:
                wrapper.eq("expense_calendar_way",1);
                break;
            case 2:
                wrapper.eq("expense_calendar_way",2);
                break;
        }
        List list = spExpenseCalendarService.list(wrapper);
        return ResponseUtil.success(PageInfo.of(list));
    }
}
